import UIKit

// 图标单元格
class IconCell: UICollectionViewCell {
    @IBOutlet weak var mImageView: UIImageView! // 图片视图
    
    /**
     * 设置图标。
     * @param index 图标索引
     */
    public func setIcon(_ index: Int) {
        // 设置图标
        let fileName = String(format: Const.ICON_FILE_NAME, index)
        mImageView.image = UIImage(named: fileName)!

        // 添加控件约束
        mImageView.translatesAutoresizingMaskIntoConstraints = false
        let lcWidth = NSLayoutConstraint(item: mImageView!, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0)
        self.addConstraint(lcWidth)
        let lcHeight = NSLayoutConstraint(item: mImageView!, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 0)
        self.addConstraint(lcHeight)
        
        // 设置选中时的高亮图标
        let imageSize = mImageView.image!.size
        let rect = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
        UIGraphicsBeginImageContext(imageSize)
        let backDrawer = UIGraphicsGetCurrentContext()!
        backDrawer.setBlendMode(.multiply)
        mImageView.image!.draw(in: rect)
        backDrawer.setAlpha(0.5)
        backDrawer.fill(rect)
        UIGraphicsEndImageContext()
        mImageView.highlightedImage = UIImage(cgImage: backDrawer.makeImage()!)
    }
}
